from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from app.core.exceptions import APIError
from app.api import auth, activity, announcement, form, system

app = FastAPI(
    title="培养指南系统API",
    description="培养指南系统的后端API服务",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(auth.router)
app.include_router(activity.router)
app.include_router(announcement.router)
app.include_router(form.router)
app.include_router(system.router)

# 全局异常处理
@app.exception_handler(APIError)
async def api_error_handler(request: Request, exc: APIError):
    return JSONResponse(
        status_code=exc.status_code,
        content=exc.detail
    )

@app.get("/")
async def root():
    return {"message": "欢迎使用培养指南系统API"} 